#include "common/pch.h"
#include "motion_generators/motion_master.h"

#include <format>

#include <cftf/loger/syslog.h>

#include "object/creature.h"
#include "object/unit.h"
#include "object/factory_selector.h"
#include "motion_generators/movement_generator.h"
#include "motion_generators/home_movement_generator.h"
#include "map/map.h"

namespace battle::motion
{

    inline bool isStatic(MovementGenerator* mv)
    {
#if 1
        return true;
#else
        return (mv == &si_idleMovement);
#endif
    }

    void MotionMaster::Initialize()
    {
        // stop current move
        m_owner->StopMoving();

        // clear ALL movement generators (including default)
        Clear(false, true);

        // set new default movement generator
        if (m_owner->GetTypeId() == TYPEID_UNIT && !m_owner->hasUnitState(UNIT_STAT_CONTROLLED))
        {
#if 0
            MovementGenerator* movement = FactorySelector::selectMovementGenerator((battle::object::Creature*)m_owner);
            push(movement == NULL ? &si_idleMovement : movement);
            top()->Initialize(*m_owner);
            if (top()->GetMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
            {
                (static_cast<WaypointMovementGenerator<battle::object::Creature>*>(top()))->InitializeWaypointPath(*((battle::object::Creature*)(m_owner)), 0, PATH_NO_PATH, 0, 0);
            }
#endif
        }
        else
        {
#if 0
            push(&si_idleMovement);
#endif
        }
    }

    MotionMaster::~MotionMaster()
    {
        // just deallocate movement generator, but do not Finalize since it may access to already deallocated owner's memory
        while (!empty())
        {
            MovementGenerator* m = top();
            pop();
            if (!isStatic(m))
            {
                delete m;
            }
        }
    }

    void MotionMaster::UpdateMotion(unsigned int diff)
    {
        if (m_owner->hasUnitState(UNIT_STAT_CAN_NOT_MOVE))
        {
            return;
        }

        CFT_ASSERT(!empty());
        m_cleanFlag |= MMCF_UPDATE;

        if (!top()->Update(*m_owner, diff))
        {
            m_cleanFlag &= ~MMCF_UPDATE;
            MovementExpired();
        }
        else
        {
            m_cleanFlag &= ~MMCF_UPDATE;
        }

        if (m_expList)
        {
            for (size_t i = 0; i < m_expList->size(); ++i)
            {
                MovementGenerator* mg = (*m_expList)[i];
                if (!isStatic(mg))
                {
                    delete mg;
                }
            }

            delete m_expList;
            m_expList = NULL;

            if (empty())
            {
                Initialize();
            }

            if (m_cleanFlag & MMCF_RESET)
            {
                top()->Reset(*m_owner);
                m_cleanFlag &= ~MMCF_RESET;
            }
        }
    }

    void MotionMaster::DirectClean(bool reset, bool all)
    {
        while (all ? !empty() : size() > 1)
        {
            MovementGenerator* curr = top();
            pop();
            curr->Finalize(*m_owner);

            if (!isStatic(curr))
            {
                delete curr;
            }
        }

        if (!all && reset)
        {
            CFT_ASSERT(!empty());
            top()->Reset(*m_owner);
        }
    }

    void MotionMaster::DelayedClean(bool reset, bool all)
    {
        if (reset)
        {
            m_cleanFlag |= MMCF_RESET;
        }
        else
        {
            m_cleanFlag &= ~MMCF_RESET;
        }

        if (empty() || (!all && size() == 1))
        {
            return;
        }

        if (!m_expList)
        {
            m_expList = new ExpireList();
        }

        while (all ? !empty() : size() > 1)
        {
            MovementGenerator* curr = top();
            pop();
            curr->Finalize(*m_owner);

            if (!isStatic(curr))
            {
                m_expList->push_back(curr);
            }
        }
    }

    void MotionMaster::DirectExpire(bool reset)
    {
        if (empty() || size() == 1)
        {
            return;
        }

        MovementGenerator* curr = top();
        pop();

        // also drop stored under top() targeted motions
        while (!empty() && (top()->GetMovementGeneratorType() == CHASE_MOTION_TYPE || top()->GetMovementGeneratorType() == FOLLOW_MOTION_TYPE))
        {
            MovementGenerator* temp = top();
            pop();
            temp->Finalize(*m_owner);
            delete temp;
        }

        // Store current top MMGen, as Finalize might push a new MMGen
        MovementGenerator* nowTop = empty() ? NULL : top();
        // it can add another motions instead
        curr->Finalize(*m_owner);

        if (!isStatic(curr))
        {
            delete curr;
        }

        if (empty())
        {
            Initialize();
        }

        // Prevent reseting possible new pushed MMGen
        if (reset && top() == nowTop)
        {
            top()->Reset(*m_owner);
        }
    }

    void MotionMaster::DelayedExpire(bool reset)
    {
        if (reset)
        {
            m_cleanFlag |= MMCF_RESET;
        }
        else
        {
            m_cleanFlag &= ~MMCF_RESET;
        }

        if (empty() || size() == 1)
        {
            return;
        }

        MovementGenerator* curr = top();
        pop();

        if (!m_expList)
        {
            m_expList = new ExpireList();
        }

        // also drop stored under top() targeted motions
        while (!empty() && (top()->GetMovementGeneratorType() == CHASE_MOTION_TYPE || top()->GetMovementGeneratorType() == FOLLOW_MOTION_TYPE))
        {
            MovementGenerator* temp = top();
            pop();
            temp->Finalize(*m_owner);
            m_expList->push_back(temp);
        }

        curr->Finalize(*m_owner);

        if (!isStatic(curr))
        {
            m_expList->push_back(curr);
        }
    }

    void MotionMaster::MoveIdle()
    {
        if (empty() || !isStatic(top()))
        {
#if 0
            push(&si_idleMovement);
#endif
        }
    }

    void MotionMaster::MoveRandomAroundPoint(float x, float y, float z, float radius, float verticalZ)
    {
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} attempt to move random.", m_owner->GetGuidStr().c_str()));
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} move random.", m_owner->GetGuidStr().c_str()));
#if 0
            Mutate(new RandomMovementGenerator<battle::object::Creature>(x, y, z, radius, verticalZ));
#endif
        }
    }

    void MotionMaster::MoveTargetedHome()
    {
        if (m_owner->hasUnitState(UNIT_STAT_LOST_CONTROL))
        {
            return;
        }

        Clear(false);

        if (m_owner->GetTypeId() == TYPEID_UNIT && !((battle::object::Creature*)m_owner)->GetCharmerOrOwnerGuid())
        {
            // Manual exception for linked mobs
            if (m_owner->IsLinkingEventTrigger() && m_owner->GetMap()->GetCreatureLinkingHolder()->TryFollowMaster((battle::object::Creature*)m_owner))
            {
                cftf::loger::SysLog::Instance().Error(std::format("{} refollowed linked master", m_owner->GetGuidStr().c_str()));
            }
            else
            {
                cftf::loger::SysLog::Instance().Error(std::format("{} targeted home", m_owner->GetGuidStr().c_str()));
                Mutate(new HomeMovementGenerator<battle::object::Creature>());
            }
        }
        else if (m_owner->GetTypeId() == TYPEID_UNIT && ((battle::object::Creature*)m_owner)->GetCharmerOrOwnerGuid())
        {
            if (battle::object::Unit* target = ((battle::object::Creature*)m_owner)->GetCharmerOrOwner())
            {
                cftf::loger::SysLog::Instance().Error(std::format("{} follow to {}", m_owner->GetGuidStr().c_str(), target->GetGuidStr().c_str()));
#if 0
                Mutate(new FollowMovementGenerator<battle::object::Creature>(*target, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE));
#endif
            }
            else
            {
                cftf::loger::SysLog::Instance().Error(std::format("{} attempt but fail to follow owner", m_owner->GetGuidStr().c_str()));
            }
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} attempt targeted home", m_owner->GetGuidStr().c_str()));
        }
    }

    void MotionMaster::MoveConfused()
    {
        cftf::loger::SysLog::Instance().Error(std::format("{} move confused", m_owner->GetGuidStr().c_str()));

#if 0
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            Mutate(new ConfusedMovementGenerator<battle::object::Player>());
        }
        else
        {
            Mutate(new ConfusedMovementGenerator<battle::object::Creature>());
        }
#endif
    }

    void MotionMaster::MoveChase(battle::object::Unit* target, float dist, float angle)
    {
        // ignore movement request if target not exist
        if (!target)
        {
            return;
        }

        cftf::loger::SysLog::Instance().Error(std::format("{} chase to {}", m_owner->GetGuidStr().c_str(), target->GetGuidStr().c_str()));

#if 0
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            Mutate(new ChaseMovementGenerator<battle::object::Player>(*target, dist, angle));
        }
        else
        {
            Mutate(new ChaseMovementGenerator<battle::object::Creature>(*target, dist, angle));
        }
#endif
    }

    void MotionMaster::MoveFollow(battle::object::Unit* target, float dist, float angle)
    {
        if (m_owner->hasUnitState(UNIT_STAT_LOST_CONTROL))
        {
            return;
        }

        Clear();

        // ignore movement request if target not exist
        if (!target)
        {
            return;
        }

        cftf::loger::SysLog::Instance().Error(std::format("{} follow to {}", m_owner->GetGuidStr().c_str(), target->GetGuidStr().c_str()));

#if 0
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            Mutate(new FollowMovementGenerator<Player>(*target, dist, angle));
        }
        else
        {
            Mutate(new FollowMovementGenerator<Creature>(*target, dist, angle));
        }
#endif
    }

    void MotionMaster::MovePoint(unsigned int id, float x, float y, float z, bool generatePath)
    {
        cftf::loger::SysLog::Instance().Error(std::format("{} targeted point (Id: {} X: {} Y: {} Z: {})", m_owner->GetGuidStr().c_str(), id, x, y, z));

#if 0
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            Mutate(new PointMovementGenerator<battle::object::Player>(id, x, y, z, generatePath));
        }
        else
        {
            Mutate(new PointMovementGenerator<battle::object::Creature>(id, x, y, z, generatePath));
        }
#endif
    }

    void MotionMaster::MoveSeekAssistance(float x, float y, float z)
    {
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} attempt to seek assistance", m_owner->GetGuidStr().c_str()));
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} seek assistance (X: {} Y: {} Z: {})",
                m_owner->GetGuidStr().c_str(), x, y, z));
#if 0
            Mutate(new AssistanceMovementGenerator(x, y, z));
#endif
        }
    }

    void MotionMaster::MoveSeekAssistanceDistract(unsigned int time)
    {
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} attempt to call distract after assistance", m_owner->GetGuidStr().c_str()));
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} is distracted after assistance call (Time: {})",
                m_owner->GetGuidStr().c_str(), time));
#if 0
            Mutate(new AssistanceDistractMovementGenerator(time));
#endif
        }
    }

    void MotionMaster::MoveFleeing(battle::object::Unit* enemy, unsigned int time)
    {
        if (!enemy)
        {
            return;
        }

        cftf::loger::SysLog::Instance().Error(std::format("{} flee from {}", m_owner->GetGuidStr().c_str(), enemy->GetGuidStr().c_str()));

#if 0
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
            Mutate(new FleeingMovementGenerator<battle::object::Player>(enemy->GetObjectGuid()));
        }
        else
        {
            if (time)
            {
                Mutate(new TimedFleeingMovementGenerator(enemy->GetObjectGuid(), time));
            }
            else
            {
                Mutate(new FleeingMovementGenerator<battle::object::Creature>(enemy->GetObjectGuid()));
            }
        }
#endif
    }

    void MotionMaster::MoveWaypoint(int id /*=0*/, unsigned int source /*=0==PATH_NO_PATH*/, unsigned int initialDelay /*=0*/, unsigned int overwriteEntry /*=0*/)
    {
        if (m_owner->GetTypeId() == TYPEID_UNIT)
        {
            if (GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
            {
                cftf::loger::SysLog::Instance().Error(std::format("{} attempt to MoveWaypoint() but is already using waypoint", m_owner->GetGuidStr().c_str()));
                return;
            }

            battle::object::Creature* creature = (battle::object::Creature*)m_owner;

            cftf::loger::SysLog::Instance().Error(std::format("{} start MoveWaypoint()", m_owner->GetGuidStr().c_str()));
#if 0
            WaypointMovementGenerator<battle::object::Creature>* newWPMMgen = new WaypointMovementGenerator<battle::object::Creature>(*creature);
            Mutate(newWPMMgen);
            newWPMMgen->InitializeWaypointPath(*creature, id, (WaypointPathOrigin)source, initialDelay, overwriteEntry);
#endif
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("Non-creature {} attempt to MoveWaypoint()", m_owner->GetGuidStr().c_str()));
        }
    }

    void MotionMaster::MoveTaxiFlight(unsigned int path, unsigned int pathnode)
    {
        if (m_owner->GetTypeId() == TYPEID_PLAYER)
        {
#if 0
            if (path < sTaxiPathNodesByPath.size())
            {
                DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "%s taxi to (Path %u node %u)", m_owner->GetGuidStr().c_str(), path, pathnode);
                FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(sTaxiPathNodesByPath[path], pathnode);
                Mutate(mgen);
            }
            else
            {
                sLog.outError("%s attempt taxi to (nonexistent Path %u node %u)",
                    m_owner->GetGuidStr().c_str(), path, pathnode);
            }
#endif
        }
        else
        {
            cftf::loger::SysLog::Instance().Error(std::format("{} attempt taxi to (Path {} node {})",
                m_owner->GetGuidStr().c_str(), path, pathnode));
        }
    }

    void MotionMaster::MoveDistract(unsigned int timer)
    {
        cftf::loger::SysLog::Instance().Error(std::format("{} distracted (timer: {})", m_owner->GetGuidStr().c_str(), timer));
#if 0
        DistractMovementGenerator* mgen = new DistractMovementGenerator(timer);
        Mutate(mgen);
#endif
    }

    void MotionMaster::MoveFlyOrLand(unsigned int id, float x, float y, float z, bool liftOff)
    {
        if (m_owner->GetTypeId() != TYPEID_UNIT)
        {
            return;
        }

        cftf::loger::SysLog::Instance().Error(std::format("{} targeted point for {} (Id: {} X: {} Y: {} Z: {})", m_owner->GetGuidStr().c_str(), liftOff ? "liftoff" : "landing", id, x, y, z));
#if 0
        Mutate(new FlyOrLandMovementGenerator(id, x, y, z, liftOff));
#endif
    }

    void MotionMaster::Mutate(MovementGenerator* m)
    {
        if (!empty())
        {
            switch (top()->GetMovementGeneratorType())
            {
                // HomeMovement is not that important, delete it if meanwhile a new comes
            case HOME_MOTION_TYPE:
                // DistractMovement interrupted by any other movement
            case DISTRACT_MOTION_TYPE:
                MovementExpired(false);
            default:
                break;
            }

            if (!empty())
            {
                top()->Interrupt(*m_owner);
            }
        }

        m->Initialize(*m_owner);
        push(m);
    }

    void MotionMaster::PropagateSpeedChange()
    {
        Impl::container_type::iterator it = Impl::c.begin();
        for (; it != end(); ++it)
        {
            (*it)->unitSpeedChanged();
        }
    }

    bool MotionMaster::SetNextWaypoint(unsigned int pointId)
    {
        for (Impl::container_type::reverse_iterator rItr = Impl::c.rbegin(); rItr != Impl::c.rend(); ++rItr)
        {
            if ((*rItr)->GetMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
            {
#if 0
                return (static_cast<WaypointMovementGenerator<battle::object::Creature>*>(*rItr))->SetNextWaypoint(pointId);
#endif
            }
        }
        return false;
    }

    unsigned int MotionMaster::getLastReachedWaypoint() const
    {
        for (Impl::container_type::const_reverse_iterator rItr = Impl::c.rbegin(); rItr != Impl::c.rend(); ++rItr)
        {
            if ((*rItr)->GetMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
            {
#if 0
                return (static_cast<WaypointMovementGenerator<battle::object::Creature>*>(*rItr))->getLastReachedWaypoint();
#endif
            }
        }
        return 0;
    }

    MovementGeneratorType MotionMaster::GetCurrentMovementGeneratorType() const
    {
        if (empty())
        {
            return IDLE_MOTION_TYPE;
        }

        return top()->GetMovementGeneratorType();
    }

    void MotionMaster::GetWaypointPathInformation(std::ostringstream& oss) const
    {
        for (Impl::container_type::const_reverse_iterator rItr = Impl::c.rbegin(); rItr != Impl::c.rend(); ++rItr)
        {
            if ((*rItr)->GetMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
            {
#if 0
                static_cast<WaypointMovementGenerator<battle::object::Creature>*>(*rItr)->GetPathInformation(oss);
#endif
                return;
            }
        }
    }

    bool MotionMaster::GetDestination(float& x, float& y, float& z)
    {
#if 0
        if (m_owner->movespline->Finalized())
        {
            return false;
        }

        const G3D::Vector3& dest = m_owner->movespline->FinalDestination();
        x = dest.x;
        y = dest.y;
        z = dest.z;
#endif
        return true;
    }

    void MotionMaster::MoveFall()
    {
        // use larger distance for vmap height search than in most other cases
        float tz = m_owner->GetMap()->GetHeight(m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ());
        if (tz <= INVALID_HEIGHT)
        {
            cftf::loger::SysLog::Instance().Deubg(std::format("MotionMaster::MoveFall: unable retrive a proper height at map {} (x: {}, y: {}, z: {}).",
                m_owner->GetMap()->GetId(), m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ()));
            return;
        }

        // Abort too if the ground is very near
        if (fabs(m_owner->GetPositionZ() - tz) < 0.1f)
        {
            return;
        }

#if 0
        Movement::MoveSplineInit init(*m_owner);
        init.MoveTo(m_owner->GetPositionX(), m_owner->GetPositionY(), tz);
        init.SetFall();
        init.Launch();
#endif
    }

}